package com.jsh.erp.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class AuthCache {
    public static Boolean isExpired = false;

    @Value("${erp.auth.code}")
    private String authCode;

    @PostConstruct
    public void init() {
        //系统启动中。。。
//        Logger logger = LoggerFactory.getLogger(AuthCache.class);
//        logger.info("AuthCache-start");
//        try {
//            //检查域名
//            InetAddress ip = InetAddress.getByName("1835986606787239.cn-shanghai.fc.aliyuncs.com");
//            String ipString = ip.getHostAddress();
//            logger.info("AuthCache-ip:{}",ipString);
//            if (ipString.equals("localhost") || ipString.equals("127.0.0.1")) {
//                isExpired = true;
//                return;
//            }
//
//            //请求授权过期时间
//            String url = "https://1835986606787239.cn-shanghai.fc.aliyuncs.com/2016-08-15/proxy/erp/auth/";
//            url += "?code=" + authCode;
//            JSONObject authObject = this.getInfo(url);
//            logger.info("AuthCache-result:{}",authObject);
//
//            //检查时间
//            Date nowDate = new Date();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            String nowDateString = sdf.format(nowDate);
//            String serverDateString = authObject.getString("now");
//            serverDateString = serverDateString.substring(0,10);
//            logger.info("AuthCache-date:{}",nowDateString);
//            if (!serverDateString.equals(nowDateString)) {
//                isExpired = true;
//                return;
//            }
//
//            //检查过期
//            if (authObject.getBoolean("expire")) {
//                isExpired = true;
//            } else {
//                isExpired = false;
//            }
//
//        } catch (Exception e) {
//            logger.error("AuthCache-error:{}", e);
//            isExpired = true;
//        }

    }

    private JSONObject getInfo(String url) {
        RestTemplate restTemplate = new RestTemplate();
        String resultStr = restTemplate.getForObject(url, String.class);
        return JSON.parseObject(resultStr);
    }

    @PreDestroy
    public void destroy() {
        //系统运行结束
    }

    //每天12点触发
    //@Scheduled(cron = "0 0 12 * * ?")
    @Scheduled(cron = "0 0 12 10,20 * ?")
    public void testOne() {
        init();
    }
}
